﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using SingleBlog.Core.Data;
using SingleBlog.Core.Services;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SingleBlog.Web.Areas.Admin.Controllers
{
    [Area("admin")]
    [Authorize(Roles = SingleBlogRole.ADMINISTRATOR)]
    public class ArticleController : Controller
    {
        private readonly ArticleService _articleService;
        private readonly CategoryService _categoryService;
        public ArticleController(ArticleService articleService,CategoryService categoryService)
        {
            _articleService = articleService;
            _categoryService = categoryService;
        }

        public async Task<IActionResult> List(int page=1,int? categoryId=null)
        {
            var list = await _articleService.GetArticlesAsync(new ArticleService.Query { Page = page, CategoryId = categoryId });
            return View(list);
        }

        public async Task<IActionResult> Edit(int? id)
        {
            var categories = await _categoryService.GetCategoriesAsync();
            var listItems = new List<SelectListItem>();
            foreach (var item in categories)
            {
                listItems.Add(new SelectListItem { Value = item.Id.ToString(), Text = item.Name });
            }

            ViewData["CategoryList"] = listItems;

            if (id.HasValue)
            {
                var article = await _articleService.GetArticleAsync(id.Value, false);
                return View(article);
            }
            return View(new Article());
        }

        [HttpPost]
        public async Task<IActionResult> Edit([FromForm]Article model)
        {
            await _articleService.SaveArticleAsync(model);
            return RedirectToAction("List");
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                await _articleService.DeleteArticleAsync(id);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
            return Ok();
        }
    }
}
